<?php

class Router
{
	private $query;
	private $indexes = array('module','action');
	private $config;
	private $twig;

	public function __construct($query,$config,$twig)
	{
		$this->config = $config;
		$this->query = array_filter(explode('/',$query));
		$this->indexes = array_merge($this->indexes, $config->routeTable);
		$this->formatQuery();
		$this->setTwig($twig);
	}

	public function formatQuery()
	{
		$temp = '';
		for($i=0; $i<sizeof($this->query);$i++)
		{
			$index = array_key_exists($i, $this->indexes) ? $this->indexes[$i] : "unnamed".($i-sizeof($this->indexes));
			$temp[$index] = $this->query[$i];
		}
		if(!empty($temp))
			$this->query = $temp;
	}

	public function setTwig($twig)
	{
		$this->twig = $twig;
		$this->twig->addGlobal('config',$this->config);
	}

	public function route($inputModule="",$inputAction="")
	{
		if($inputModule!="")
		{
			$module = $inputModule;
		}
		elseif(sizeof($this->query)==0)
		{
			$module = $this->config->standaardModule;
		}
		else
		{
			$module = $this->query['module'];
		}

		$file = $this->config->path->root.'modules/'.$module.'/'.$module.'Module.php';


		if(file_exists($file))
		{
			require($file);
			$moduleName = $module.'Module';
			$module = new $moduleName($this->query,$this->twig);

			if(!isset($this->query['action']))
			{
				$this->query['action'] = 'index';
			}

			$action = $this->query['action'] . 'Action';

			if(method_exists($module, $action))
			{
				return $module->$action();
			}
			else
			{
				die('Router broke. Function bestaat niet!!');
			}

		}
		else
		{
			die('Module bestaat niet..... Doh');
		}
	}
}

?>